package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.NearbyPeopleAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.NeartyPeopleEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.greendao.Friends;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.socks.library.KLog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_NEARBY_PEOPLE;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;

/**
 * 附近的人
 */
public class NeartyPeopleActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    @BindView(R.id.ll_back)
    LinearLayout mLlBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.rl_title_root)
    RelativeLayout mRlTitleRoot;
    @BindView(R.id.tv_right_img_btn)
    TextView mTvRightImgBtn;
    @BindView(R.id.tv_save_address)
    TextView mTvSaveAddress;
    @BindView(R.id.tv_submit)
    TextView mTvSubmit;
    @BindView(R.id.iv_right_icon)
    ImageView mIvRightIcon;
    @BindView(R.id.ll_right)
    LinearLayout mLlRight;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.ll_list)
    LinearLayout mLlList;
    @BindView(R.id.sw_finish)
    SwipeBackLayout mSwFinish;
    @BindView(R.id.view_empty)
    View view_empty;

    private String toAddUsername;
    private ProgressDialog progressDialog;
    private NearbyPeopleAdapter mNearbyPeopleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nearty_people);
        ButterKnife.bind(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        mTvTitle.setText(R.string.text_nearty_people);
        initAdapter();

    }

    @Override
    protected void initData() {
        getDate();
    }

    @Override
    protected void initEvent() {
        mSwFinish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        mNearbyPeopleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                NeartyPeopleEntity.DataBean.ListBean listBean =
                        (NeartyPeopleEntity.DataBean.ListBean) adapter.getData().get(position);
                String user_id = String.valueOf(listBean.getUser_id());
                switch (view.getId()) {
                    case R.id.iv_user_head:
                        KLog.e(user_id);
                        startLocalActivity(NeartyPeopleActivity.this, UserInfoActivity.class, PARAMS_USER_INFO, user_id);
                        break;
                    case R.id.add_friend:
                        toAddUsername = String.valueOf(user_id);
                        addContact();
                        break;
                }
            }
        });
    }

    private void initAdapter() {
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        mSwipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        mRvList.setLayoutManager(new MyLinearLayoutManager(this));
        mNearbyPeopleAdapter = new NearbyPeopleAdapter();
        mNearbyPeopleAdapter.openLoadAnimation();
        mNearbyPeopleAdapter.setOnLoadMoreListener(this);
        mRvList.setAdapter(mNearbyPeopleAdapter);
    }

    private void getDate() {
        OkHttpUtils.get().url(URL_NEARBY_PEOPLE)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", PARAMS_PAGE_SIZE)
                .addParams("city_id", SPUtil.getUserLocation().getCityId())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                mSwipeLayout.setRefreshing(false);
                NeartyPeopleEntity neartyPeopleEntity = GsonUtil.fromJson(response, NeartyPeopleEntity.class);
                if (neartyPeopleEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    mNearbyPeopleAdapter.setNewData(neartyPeopleEntity.getData().getList());
                    isEnd = neartyPeopleEntity.getData().getIs_end();
                    if (page == 1) {

                        if (neartyPeopleEntity.getData().getList().size() == 0)
                            view_empty.setVisibility(View.VISIBLE);
                        else {
                            view_empty.setVisibility(View.GONE);
                            mNearbyPeopleAdapter.setNewData(neartyPeopleEntity.getData().getList());
                        }

                    } else {
                        mNearbyPeopleAdapter.addData(neartyPeopleEntity.getData().getList());
                        mNearbyPeopleAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                mSwipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    @Override
    public void onRefresh() {
        mNearbyPeopleAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mNearbyPeopleAdapter.getData().clear();
                getDate();
                mNearbyPeopleAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    mNearbyPeopleAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getDate();
                    } else {
                        isErr = true;
                        ShowToast.showShortToast(R.string.network_anomalies);
                        mNearbyPeopleAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    /**
     * add contact
     */
    public void addContact() {

        Friends friends = FriendsCache.getInstance(this).getCacheByName(toAddUsername);
        if (null == friends) {
            friends = new Friends();
            friends.setUser_id("");
        }

        if (toAddUsername.equals(SPUtil.getUser().getData().getUser_id())) {
            new EaseAlertDialog(this, com.eightbears.beboy.R.string.not_add_myself).show();
            return;
        }

        if (toAddUsername.equals(friends.getUser_id())) {
            if (EMClient.getInstance().contactManager().getBlackListUsernames().contains(toAddUsername)) {
                new EaseAlertDialog(this, R.string.user_already_in_contactlist).show();
                return;
            }
            new EaseAlertDialog(this, com.eightbears.beboy.R.string.This_user_is_already_your_friend).show();
            return;
        }
        progressDialog = new ProgressDialog(this);
        String stri = getResources().getString(com.eightbears.beboy.R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    //demo use a hardcode reason here, you need let user to input if you like
                    String s = getResources().getString(com.eightbears.beboy.R.string.Add_a_friend);
                    EMClient.getInstance().contactManager().addContact(toAddUsername, s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources().getString(com.eightbears.beboy.R.string.send_successful);
                            Toast.makeText(getApplicationContext(), s1, Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(com.eightbears.beboy.R.string.Request_add_buddy_failure);
                            Toast.makeText(getApplicationContext(), s2 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }
}